<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Jobs\AnswerActivityDrawJob;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 用户获取礼物表
 */

class AnswerActivityUserGift extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_gift';

    /**
     * 获取用户礼物列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param act_id int 活动id
     * @param user_guid int 用户id
     * @param keywords string 搜索关键词
     * @param unit_id int 单位id
     * @param type int 1文化红包 2精美礼品
     * @param state string 礼物状态 1未发放 2已发放 3未发货 4邮递中 5已到货 6 未领取 7 已领取  8 红包发放中
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     */
    public function lists($act_id, $user_guid = null, $keywords = null, $type = null, $state = null, $unit_id = null, $start_time = null, $end_time = null, $page = 1, $limit = 10)
    {
        $res = $this->from('answer_activity_user_gift as ug')
            ->select(
                'ug.id',
                'ug.user_guid',
                'ug.order_id',
                'ug.state',
                'ug.gift_id',
                'ug.date',
                'ug.type',
                'ug.create_time',
                'g.unit_id',
                'g.name',
                'g.img',
                'g.intro',
                'g.price',
                'g.way',
                'g.start_time',
                'g.end_time',
                'g.tel',
                'g.contacts',
                'g.province',
                'g.city',
                'g.district',
                'g.address',
                'g.remark'
            )
            ->join('answer_activity_gift as g', 'g.id', '=', 'ug.gift_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->Orwhere('ug.order_id', 'like', '%' . $keywords . '%')->Orwhere('g.name', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($user_guid, $type, $state, $unit_id, $start_time, $end_time) {
                if ($user_guid) {
                    $query->where('user_guid', $user_guid);
                }
                if ($unit_id || $unit_id === 0 || $unit_id === '0') {
                    $query->where('unit_id', $unit_id);
                }
                if ($type) {
                    $query->where('ug.type', $type);
                }
                if ($state) {
                    $query->where('ug.state', $state);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('ug.create_time', [$start_time, $end_time]);
                }
            })->where('ug.act_id', $act_id)
            ->where('g.is_del', 1)
            ->orderByDesc('ug.id')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);

        return $res;
    }

    /**
     * 获取中奖数量
     * @param act_id 活动id
     * @param user_guid 用户id
     * @param type 1文化红包 2精美礼品 
     * @param date 日期
     * @param hour 小时
     * @param unit_id 单位id  数组形式
     */
    public function getWinNumber($act_id, $user_guid = null, $type = null, $date = null, $hour = null, $start_time = null, $end_time = null, $unit_id = [])
    {
        $gift_id = [];
        //获取所有满足条件的礼物id
        $answerActivityGiftModel = new AnswerActivityGift();
        $gift_id = $answerActivityGiftModel->where(function ($query) use ($act_id, $type, $unit_id) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($type) {
                $query->where('type', $type);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
        })->where('is_del', 1)
            ->pluck('id')
            ->toArray();

        $res = $this->where(function ($query) use ($act_id,$user_guid, $type, $date, $hour, $gift_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($user_guid) {
                $query->where('user_guid', $user_guid);
            }
            if ($type) {
                $query->where('type', $type);
            }
            if ($date) {
                $query->where('date', $date);
            }
            if ($hour) {
                $query->where('hour', $hour);
            }
            if ($gift_id) {
                $query->whereIn('gift_id', $gift_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->whereIn('gift_id', $gift_id)
        ->count();

        return $res;
    }

    /**
     * 答题次数统计(折线图)
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     */
    public function giftStatistics($act_id, $unit_id = [], $type = null, $start_time = null, $end_time = null)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }
        
        $gift_id = [];
        if ($unit_id) {
            //获取所有满足条件的礼物id
            $answerActivityGiftModel = new AnswerActivityGift();
            $gift_id = $answerActivityGiftModel->where('act_id', $act_id)->where(function ($query) use ($type) {
                if ($type) {
                    $query->where('type', $type);
                }
            })->whereIn('unit_id', $unit_id)
                ->pluck('id')
                ->toArray();
        }

        if (date('Y-m-d' , strtotime($start_time)) == date('Y-m-d' , strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as count")];
        }

        $res = $this->select($field)->where(function ($query) use ($type, $gift_id, $start_time, $end_time) {
            if ($type) {
                $query->where('type', $type);
            }
            if ($gift_id) {
                $query->whereIn('gift_id', $gift_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->where('act_id', $act_id)
            ->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();

        return $res;
    }

    /**
     * 判断用户今日是否还有获奖机会
     * @param act_id 活动id
     * @param user_guid 用户guid
     */
    public function isDayWinChance($act_id, $user_guid, $type)
    {
        $date = date('Y-m-d');
        //获取今日获奖总个数
        $max_number_day = $this->getWinNumber($act_id, null, $type, $date);//所有用户今日获奖个数
        $user_number_day = $this->getWinNumber($act_id, $user_guid, $type, $date);//某个用户今日获奖个数

        if ($type == 1) {
            if (AnswerActivityDrawJob::$red_max_number_day <= $max_number_day) {
                return false; //红包今日发放完毕
            }
            if (AnswerActivityDrawJob::$user_red_number_day <= $user_number_day) {
                return false; //红包用户今日发放完毕
            }
        } else {
            if (AnswerActivityDrawJob::$gift_max_number_day <= $max_number_day) {
                return false; //礼物今日发放完毕
            }
            if (AnswerActivityDrawJob::$user_gift_number_day <= $user_number_day) {
                return false; //礼物用户今日发放完毕
            }
        }
        return true; //可以获得
    }

    /**
     * 判断用户当前时间段是否还有获奖机会
     * @param type 1文化红包 2精美礼品 
     * @param act_id 活动id
     * @param user_guid 用户guid
     */
    public function isTimeQuantumWinChance($act_id, $user_guid, $type)
    {
        $time_quantum_data = AnswerActivityGiftTime::getTimeQuantumData($act_id, $type);
        if (empty($time_quantum_data)) {
            return true; //时间段未设置，则直接可以获取
        }
        //获取总发放数量
        $total_gift_number_time_quantum = $this->getWinNumber($act_id, null, $type, null, null, $time_quantum_data['start_time'], $time_quantum_data['end_time']);
        if ($total_gift_number_time_quantum >= $time_quantum_data['number']) {
            return false;
        }
        //获取用户发放数量
        $user_gift_number_time_quantum = $this->getWinNumber($act_id, $user_guid, $type, null, null, $time_quantum_data['start_time'], $time_quantum_data['end_time']);
        if ($user_gift_number_time_quantum >= $time_quantum_data['user_gift_number']) {
            return false;
        }
        return true;
    }

    /**
     * 根据订单号，获取用户中奖信息
     * @param order_id 订单号
     */
    public function getUserGiftInfo($order_id)
    {
        //获取奖品
        $user_gift = $this->where('order_id', $order_id)->first();
        if (empty($user_gift)) {
            return false; //'未中奖，请下次再来';
        }
        //获取对应礼物
        $gift_info = AnswerActivityGift::select(
            'name',
            'img',
            'intro',
            'total_number',
            'percent',
            'type',
            'price',
            'way',
            'start_time',
            'end_time',
            'tel',
            'contacts',
            'province',
            'city',
            'district',
            'address',
            'remark'

        )->where('id', $user_gift['gift_id'])->where('act_id', $user_gift['act_id'])->where('is_del', 1)->first();
        if (empty($gift_info)) {
            return false; //'未中奖，请下次再来';//礼物不存在
        }
        $gift_info = $gift_info->toArray();
        $gift_info['create_time'] = $user_gift['create_time']; //中奖时间
        $gift_info['state'] = $user_gift['state']; //礼物状态 1未发放 2已发放 3未发货 4邮递中 5已到货
        $gift_info['pay_time'] = $user_gift['pay_time']; //红包到账时间 ,红包类型才有，其他无

        return $gift_info;
    }

    /**
     * 奖品领取或发奖
     * @param ids 奖品id 多个逗号拼接
     * @param state 奖品id 4 已发货  7 已领取
     */
    public function giftGrant($ids,$state){
        $ids = explode(',' , $ids);
        foreach($ids as $key=>$val){
            $user_gift_info = $this->where('id' , $val)->first();
            if(empty($user_gift_info)){
                throw new Exception('礼品不存在');
            }
            if(($state == 4 && $user_gift_info['state'] != 3) || ($state == 7 && $user_gift_info['state'] != 6)){
                throw new Exception('操作状态有误');
            }
            $user_gift_info->state = $state;
            $user_gift_info->save();
        }
        return true;
    }
    
}
